package neu.soft.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import neu.soft.entity.DO.ZipCode;
import neu.soft.entity.Vendor;
import neu.soft.exception.AppException;
import neu.soft.exception.AppExceptionCodeMsg;
import neu.soft.mapper.VendorMapper;
import neu.soft.query.BasePageQuery;
import neu.soft.service.RegionService;
import neu.soft.service.VendorService;
import neu.soft.vo.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class VendorServiceImpl implements VendorService {

    @Autowired
    VendorMapper vendorMapper;

    @Autowired
    RegionService regionServicel;

    @Override
    public int addVendor(Vendor vendor) {

        int res = vendorMapper.addVendor(vendor);
        if (res < 1) {
            throw new AppException(AppExceptionCodeMsg.DZYJ_NGDZ);
        }
        return res;
    }

    @Override
    public int updateVendor(Vendor vendor) {

        if (vendor.getVendorId() == null) {
            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }
        ZipCode zipCode = regionServicel.find(vendor.getVendorAddress());
        vendor.setZip(zipCode.getZipNumber());
        int res = vendorMapper.updateVendor(vendor);
        if (res < 1) {
            throw new AppException(AppExceptionCodeMsg.YYDZ_JDWGXSB);
        }
        return res;
    }

    @Override
    public int deleteVendor(Integer vendorId) {

        int res = vendorMapper.deleteVendor(vendorId);
        if (res < 1) {
            throw new AppException(AppExceptionCodeMsg.NSRAD_JSNDSH);
        }
        return res;
    }

    @Override
    public List<Vendor> findAll() {

        return vendorMapper.findAll();
    }

    @Override
    public Vendor findById(Integer vendorId) {

        return vendorMapper.findById(vendorId);
    }

    @Override
    public Vendor findByName(String vendorName) {

        return vendorMapper.findByName(vendorName);
    }

    @Override
    public PageBean<Vendor> findByPage(BasePageQuery query) {

        PageBean<Vendor> pageBean = new PageBean<>();
        PageHelper.startPage(query.getPageNow(), query.getPageSize());
        List<Vendor> vendorList = vendorMapper.findByPage(query);
        PageInfo<Vendor> pageInfo = new PageInfo<>(vendorList);
        pageBean.setTotalRows(pageInfo.getTotal());
        pageBean.setTotalPages(pageInfo.getPages());
        pageBean.setRowData(pageInfo.getList());
        return pageBean;
    }
}
